﻿namespace RL
{
    using System;
    using System.ComponentModel;
    using System.Globalization;

    public class SizeOfCanConverter : ExpandableObjectConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return (object.ReferenceEquals(sourceType, typeof(string)) || base.CanConvertFrom(context, sourceType));
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return (object.ReferenceEquals(destinationType, typeof(SizeOfCan)) || base.CanConvertFrom(context, destinationType));
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                try
                {
                    string str = value.ToString();
                    SizeOfCan can = new SizeOfCan();
                    string[] strArray = str.Split(new char[] { ',' });
                    if (strArray != null)
                    {
                        if (strArray[0] != null)
                        {
                            can.Height = Convert.ToInt16(strArray[0]);
                        }
                        if (strArray[1] != null)
                        {
                            can.Width = Convert.ToInt16(strArray[1]);
                        }
                    }
                    return can;
                }
                catch (Exception)
                {
                    throw new ArgumentException("This value cannot be converted to a SizeOfCan.");
                }
            }
            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (object.ReferenceEquals(destinationType, typeof(string)) && (value is SizeOfCan))
            {
                SizeOfCan can = (SizeOfCan) value;
                return (can.Height + ", " + can.Width);
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}

